﻿using AuthCenter.API.Application.Command.RoleMenu;
using AuthCenter.Domain.Menu;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;
using Yitter.IdGenerator;

namespace AuthCenter.API.Application.Handler.RoleMenu
{
    public class CreateRoleMenuHandler : IRequestHandler<CreateRoleMenuCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleMenuModel> rolemenuRepo;
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IBaseRepository<RoleMenuModel> roleRepo;
        private readonly IMapper mapper;

        public CreateRoleMenuHandler(IBaseRepository<RoleMenuModel> rolemenuRepo,
                                     IBaseRepository<MenuModel> menuRepo,
                                     IBaseRepository<RoleMenuModel> roleRepo,
                                     IMapper mapper)
        {
            this.rolemenuRepo = rolemenuRepo;
            this.menuRepo = menuRepo;
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(CreateRoleMenuCommand request, CancellationToken cancellationToken)
        {

            APIResult<int> result = new APIResult<int>();
            var res = rolemenuRepo.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
            int r = 0;    
            foreach (var item in res)
            {
                r = rolemenuRepo.DeleteAsync(item).Result;
            }
            var list = request.MenuId.Split(',').Select(x => Convert.ToInt64(x)).ToList();

            int r1 = 0;
            foreach (var item in list)
            {
                RoleMenuModel roleMenu = new RoleMenuModel()
                {
                    Id = YitIdHelper.NextId(),
                    RoleId = request.RoleId,
                    MenuId = item
                };
                r1 = rolemenuRepo.AddAsync(roleMenu).Result;
            }
            if (r1 > 0)
            {
                result.Message = "分配权限成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "分配权限失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
